/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backingbeans;

import entities.UUser;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.print.attribute.standard.Severity;
import sessions.UserManager;
import utils.ClientMessage;
import utils.FormValidation;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
@ManagedBean(name = "login")
@RequestScoped
public class Login {
    @EJB
    private UserManager userManager;
    
    @ManagedProperty(value="#{userSession}")
    private UserSession userSession;
        
    private String email;
    private String pwd;
    

    public UserSession getUserSession() {
        return userSession;
    }

    public void setUserSession(UserSession userSession) {
        this.userSession = userSession;
    }
    
    
    //
    // Accessors
    //
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
    public String login() 
    {
        //Check email
        //
        if(FormValidation.validateEmailRegex(email)==false)
        {
            ClientMessage.sendClientMessage("L'adresse email que vous avez entrée est invalide", FacesMessage.SEVERITY_ERROR);
            return "index";
        }
        
        //Check password
        //
        if(pwd.length() < 6)
        {
            ClientMessage.sendClientMessage("La longueur du mot de passe doit être d'au moins 6 caractères", FacesMessage.SEVERITY_ERROR);
            return "index";
        }
        
        UUser user = userManager.getUser(email, pwd);
        
        if(user != null) 
        {
            userSession.login(user);
            System.out.println("############# CONNECTE : " + userSession.getUser().getEmail() + " ###################");
            
            return "listallsongs?faces-redirect=true&amp;includeViewParams=true";
        }
        else 
        {
            System.out.println("############ LOGIN NOK");                      
            FacesMessage fm = new FacesMessage("Email ou mot de passe incorrect");
            fm.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage("Email ou mot de passe incorrect", fm);
            
            return "index";
        }
    }
    
    public String logout() {
        userSession.logout();
        return "index?faces-redirect=true&amp;includeViewParams=true";
    }
}
